<?php
namespace backend\services;

use backend\models\AdminMenu;
use yii\log\Logger;
use Yii;
class AdminMenuService extends AdminMenu{

    public static $TYPE_MODULE = 'module';
    public static $TYPE_MENU = 'menu';
    public static $TYPE_RIGHT = 'right';
    public static $TYPE_RIGHT_URL = 'right_url';

    public function saveRightUrls($rightUrls, $right, $userName)
    {
        $insertData = array();
        $date = date('Y-m-d H:i:s');

        $connection = $this->getDb();
        $transaction = $connection->beginTransaction();
        try {
            $rightId = $right->id;
            $d = $this->getDb()->createCommand()->delete($this->tableName(), "pid = $rightId ")->execute();
            if(count($rightUrls) > 0){
                foreach($rightUrls as $url){
                    $data = array('type'=>'right_url', 'pid'=>$rightId, 'path'=>$right->path . $rightId . '_' ,
                        'name'=>$url['c'].'/'.$url['a'], 'entry_url'=>$url['c'].'/'.$url['a'],'weight'=>0,
                        'create_user'=>$userName,'create_date'=>$date, 'update_user'=>$userName, 'update_date'=>$date);
                    $insertData[] = $data;
                }
                $d = $this->getDb()->createCommand()
                    ->batchInsert($this->tableName(), [
                        'type',
                        'pid',
                        'path',
                        'name',
                        'entry_url',
                        'weight',
                        'create_user',
                        'create_date',
                        'update_user',
                        'update_date'
                    ], $insertData)
                    ->execute();
            }
            $transaction->commit();
            return $d;
        } catch (\Exception $e) {
            $transaction->rollBack();
            Yii::getLogger()->log($e->getMessage (), Logger::LEVEL_ERROR);
            return 0;
        }
        return 0;

    }

    /**
     * 取用户所有模块
     */
    public function getUserModuleList2($userId=0)
    {
        $sql = " SELECT m.id, m.pid, m.ico, m.type, m.name, m.entry_url FROM ".$this::tableName()." as m ";

//        if($userId != 0){
//        }
        $sql .= " order by weight desc ";
        $connection = Yii::$app->db;
        $command=$connection->createCommand($sql);
        $rows=$command->queryAll();
        //         $rows=$dataReader->readAll();
        return $rows;
    }
}
